package top.kangyaocoding.ecommerce.impl;

import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import top.kangyaocoding.ecommerce.IMailService;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 描述: 邮件服务实现
 *
 * @author K·Herbert
 * @since 2025-02-18 下午5:56
 */
@Slf4j
@Service
public class MailService implements IMailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Override
    public void sendTextMailMessage(String to, String subject, String text) {
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人，1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            log.info("发送Text邮件成功：{}->{}", sendMailer, to);
        } catch (MessagingException e) {
            log.error("发送Text邮件失败：{}->{}。Error：{}", sendMailer, to, e.getMessage());
        }
    }

    @Override
    public void sendHtmlMailMessage(String to, String subject, String content) {
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            mimeMessageHelper.setFrom(sendMailer);
            mimeMessageHelper.setTo(to.split(","));
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content, true); // 设置 HTML 内容
            mimeMessageHelper.setSentDate(new Date());
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            log.info("发送HTML邮件成功：{}->{}", sendMailer, to);
        } catch (MessagingException e) {
            log.error("发送HTML邮件失败：{}->{}。Error：{}", sendMailer, to, e.getMessage());
        }
    }

    @Override
    public void sendAttachmentMailMessage(String to, String subject, String content, String filePath) {
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容   true 代表支持html
            mimeMessageHelper.setText(content, true);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //添加邮件附件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();

            if (fileName != null) {
                mimeMessageHelper.addAttachment(fileName, file);
            }
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            log.info("发送附件邮件成功：{}->{}", sendMailer, to);
        } catch (MessagingException e) {
            log.error("发送附件邮件失败：{}->{}。Error：{}", sendMailer, to, e.getMessage());
        }
    }

    @Override
    public void sendVerificationEmail(String to, String verificationCode) {
        try {
            // 加载模板并替换验证码
            String htmlContent = loadTemplate("verification_email_template.html", verificationCode);
            sendHtmlMailMessage(to, "验证码通知-用户行为分析系统", htmlContent);
        } catch (IOException e) {
            log.error("加载电子邮件模板异常： {}", e.getMessage());
        }
    }

    private String loadTemplate(String templateName, String verificationCode) throws IOException {
        // 从类路径加载模板文件
        ClassPathResource resource = new ClassPathResource("templates/" + templateName);
        try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
            String templateContent = FileCopyUtils.copyToString(reader);
            // 替换动态内容
            return templateContent.replace("${verificationCode}", verificationCode);
        }
    }
}
